css:
.close { width: 30px; height: 20px; background: white; position: absolute; right: 0; top: 0; z-index: 999; font-size: 12px; text-align: center; line-height: 20px; cursor: pointer; font-family: '微软雅黑'; }
js:【修改了一些bug】
window.onload = function () { /* 参数 1. 创建飘窗,填写飘窗的id; 2. 选择该飘窗是否显示,true显示,false不显示,默认为false,不显示; 3. 该飘窗的配置信息, xPos,yPos 飘窗的起始位置,默认为左上角, imgWidth,imgHeight 飘窗的大小,默认为w: 310,h: 200, href 要跳转的链接,默认不跳转, imgSrc 图片的链接,默认为空。 */ var fl1 = new FloatWindow('win', true, { xPos: 100, yPos: 100, href: 'http://websong.wang', imgSrc: 'https://bpic.588ku.com/art_origin_min_pic/18/07/08/02ced7cd66e3a1341391af9ceb90ec62.jpg' }); } var FloatWindow = function (ele, flag, config) { flag = flag ? true : false; this.opt = this.extend({ xPos: 0, yPos: 0, imgWidth: 100, imgHeight: 100, href: 'javascript:void(0)', imgSrc: '', step: 1, height: 0, Hoffset: 0, Woffset: 0, xon: 0, yon: 0 }, config); var html = '' + '' + '' + '' + ' 关闭 ' + ''; var div = document.createElement('div'); div.innerHTML = html; if (flag) { document.body.appendChild(div); } else { return; } if (document.querySelector('#'+ele).length <= 0) { return; } this.ele = document.querySelector('#'+ele); this.interval; this.delay = 10; this.ele.querySelector('img').style['width'] = this.opt.imgWidth + 'px'; this.ele.querySelector('img').style['height']= this.opt.imgHeight + 'px'; var _self = this; this.ele.onmouseout = function () { _self.start(); } this.ele.onmouseover = function () { _self.stop(); } this.ele.onclick = function (e) { if (e.target.className === 'close') _self.stop(); document.body.removeChild(div); } changePos = function (ele, moveCfg) { width = document.documentElement.clientWidth || document.body.clientWidth; height = document.documentElement.clientHeight || document.body.clientHeight; Hoffset = ele.offsetHeight; Woffset = ele.offsetWidth; if (moveCfg.yon) { moveCfg.yPos = moveCfg.yPos + moveCfg.step; } else { moveCfg.yPos = moveCfg.yPos - moveCfg.step; } if (moveCfg.yPos < 0) { moveCfg.yon = 1; moveCfg.yPos = 0; } if (moveCfg.yPos >= (height - Hoffset)) { moveCfg.yon = 0; moveCfg.yPos = (height - Hoffset); } if (moveCfg.xon) { moveCfg.xPos = moveCfg.xPos + moveCfg.step; } else { moveCfg.xPos = moveCfg.xPos - moveCfg.step; } if (moveCfg.xPos < 0) { moveCfg.xon = 1; moveCfg.xPos = 0; } if (moveCfg.xPos >= (width - Woffset)) { moveCfg.xon = 0; moveCfg.xPos = (width - Woffset); } ele.style.left = moveCfg.xPos + document.body.scrollLeft + "px"; ele.style.top = moveCfg.yPos + document.documentElement.scrollTop + "px"; } this.start(); } FloatWindow.prototype.start = function () { var that = this; this.ele.visibility = 'visible'; this.interval = setInterval(function () { changePos(that.ele, that.opt); }, this.delay); } FloatWindow.prototype.stop = function () { clearInterval(this.interval) } FloatWindow.prototype.extend = function (o, e) { for (var key in e) { if (e[key]) { o[key] = e[key]; } } return o; }